package cn.edu.jxau.core.service;

import java.io.File;

import java.io.IOException;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;



import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.jxau.core.controller.ServiceResultConfig;
import cn.edu.jxau.core.domain.Freeze;
import cn.edu.jxau.core.exception.ServiceException;
import cn.edu.jxau.core.util.DateUtils;
import cn.edu.jxau.core.util.StringUtil;
import cn.edu.jxau.core.util.mail.Mail;
import cn.edu.jxau.core.util.mail.SendEmail;
import cn.edu.jxau.framework.dao.core.Session;
import cn.edu.jxau.framework.dao.core.sqlSessionFactory;
import cn.edu.jxau.framework.dao.exception.ConfigurationException;

/**
 * 用户业务类 UserService
 * 
 * @author zclong 2017年8月23日
 */
public class UserService extends ServiceSupport {
	private final String ERROR_MSG = "数据异常";
	private final String LOGIN_MSG = "login_msg";
	private final String EMAIL_REGEX = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
	private final String IDCARD = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
	// 日志信息
	private Logger logger = LoggerFactory.getLogger(UserService.class);
	// 保存验证码
	private static Map<String, String> verification = new HashMap();

	public UserService() {
	}

	public UserService(String view, Map<String, Object[]> params, Map<String, Object> data) throws ServiceException {
		/**
		 * view service.xml中的name和视图对应 params request入口的参数数组 data
		 * 返回给Servlet的出口参数
		 */
		super(view, params, data);
		execute(view, params, data); // 执行业务
	}

	/**
     * 登录
     * 
     * @zclong
     * @2017年8月23日
     * @ReturnType: void
     * @param params
     * @param data
     */
    @SuppressWarnings("unchecked")
    protected void login(Map<String, Object[]> params, Map<String, Object> data) {

        Map<String, Object> param = new HashMap<String, Object>(); //用来封装传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList();  // 用来接收数据库返回回来的 
        
        /**
         * 1，获取前台传过来数据
         * params : request的入口参数数组，Map集合
         * "username" : Map数组的key，通过它获取对应的值，即用户名
         * 0 : 因为是Map集合，即一个key对应的value是一个数组，所以给定数值的下标，获取对应得值，如果数组中只有一，则下标位0
         */
        int errorCount = 0; // 统计登录错误次数
        String username = getParamStringValue(params, "username", 0).trim();
        String password = getParamStringValue(params, "password", 0).trim();
        String loginErrorCount = getParamStringValue(params, "errorCount", 0).trim(); // 获取错误次数
        // 处理登入错误次数
        if (StringUtil.isBlank(loginErrorCount) || "NaN".equals(loginErrorCount)) {
            errorCount = 0;
        } else {
            errorCount = Integer.parseInt(loginErrorCount);
        }
        
        //2，校验数据
        //用户名（邮箱）验证
        if(StringUtil.isBlank(username) || !username.matches(EMAIL_REGEX)) {
            data.put(LOGIN_MSG, ERROR_MSG);
            data.put("result", ServiceResultConfig.FAILED);
            return;
        } else {
            param.put("username", username);
        }
        
        //密码验证
        if(StringUtil.isBlank(password) || password.length() > 16) {
            data.put(LOGIN_MSG, ERROR_MSG);
            data.put("result", ServiceResultConfig.FAILED);
            return;
        }else {
            param.put("password", password);
        }
        
        //数据库操作
        Session session = null;
        //查询数据库
        try {
            session = sqlSessionFactory.getInstance().getSession();
            session.execute("queryUser", param, datas);
            if(null == datas || datas.isEmpty()) {
                data.put("errorCount", errorCount+1); // 记录登录失败次数
                data.put(LOGIN_MSG, "您用户名或密码输入错误");
                data.put("result", ServiceResultConfig.FAILED);
                return;
            } else {
                int status = (int) datas.get(0).get("status");
                if(2 == status) { // 正常离线
                    data.put("session_user", datas.get(0));
                    param.clear();
                    status = 1;
                    int userID = (int) datas.get(0).get("userID");
                    param.put("status", status); 
                    param.put("userID", userID);
                    session.execute("updateUserStatus", param, datas); // 用户登录后改变 账号状态为正常在线状态
                    // 保存session的数据
                    data.put("errorCount", 0); // 登录成功记录登录失败次数为0
                    data.put("status", status); // 记录为重复登录，进行特殊处理
                    data.put("userID", userID);
                    data.put("result", ServiceResultConfig.LOGIN);
                } else { 
                    if(status == 1) { // 正常在线
                        data.put("session_user", datas.get(0));
                        param.clear();
                        status = 1;
                        int userID = (int) datas.get(0).get("userID");
                        param.put("status", status); 
                        param.put("userID", userID);
                        session.execute("updateUserStatus", param, datas); // 用户登录后改变 账号状态为正常在线状态
                        // 保存session的数据
                        data.put("errorCount", 0); // 登录成功记录登录失败次数为0
                        data.put("status", status); // 记录为重复登录，进行特殊处理
                        data.put("userID", userID);
                        //data.put(LOGIN_MSG, "您已登录，重新登录将强制退出原来用户！");
                        data.put("result", ServiceResultConfig.LOGIN);
                        return;
                    } else {
                        data.put(LOGIN_MSG, "您已被冻结，需登录请申请解冻或联系管理员！");
                        data.put("result", FAILED);
                        return;
                    }
                }
                
            }
            
            } catch (Exception e) {
            e.printStackTrace();
        }finally {
          //释放会话
            session.releaseConnection();
        }
    }

	/**
	 * 显示用户信息
	 * 
	 * @param params
	 * @param data
	 */
	@SuppressWarnings("unchecked")
	private void displayUserInfo(Map<String, Object[]> params, Map<String, Object> data) {
		
		userInfo(params,data);
		// 得到count，根据count的值选择跳转的页面
		String count = getParamStringValue(params, "count", 0);
		if (count.equals("1")) {
			data.put("result", SUCCESS);
		} else if (count.equals("2")) {
			data.put("result", ServiceResultConfig.FAILED);
		}
	}
	private void userInfo(Map<String, Object[]> params, Map<String, Object> data){
		String userID = getParamStringValue(params, "userID", 0);
		String PersonUserID = getParamStringValue(params, "PersonUserID", 0);
		//查看用户非其他用户详细信息传递的参数PersonUserID，如果不为空，替换userID
		if(PersonUserID!=null){
			userID = PersonUserID;
		}
		
		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		param.put("userID", userID);

		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的
		Session session = null;
		try {
			session = sqlSessionFactory.getInstance().getSession();
			session.execute("queryUserByID", param, datas);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 finally{
	       	 //释放会话
	           session.releaseConnection();
	       }
		// 将个人地址省市县区用正则分隔
		String address = (String) datas.get(0).get("personAddress");
		String[] personAddress = address.split("/");
		datas.get(0).replace("personAddress", personAddress);
		
		data.put("data", datas);
		 
	}
	/**
	 * 修改密码
	 * @param params
	 * @param data
	 */
	@SuppressWarnings("unchecked")
	protected void updatePassword(Map<String, Object[]> params, Map<String, Object> data) {
		String userID = getParamStringValue(params, "userID", 0);

		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		param.put("userID", userID);

		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的
		Session session = null;
		try {
			session = sqlSessionFactory.getInstance().getSession();
			session.execute("queryUserByID", param, datas);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 将个人地址省市县区用正则分隔
		String address = (String) datas.get(0).get("personAddress");
		String[] personAddress = address.split("/");
		datas.get(0).replace("personAddress", personAddress);
		System.out.println(getParamStringValue(params, "oldPassword", 0));
		data.put("data", datas);

		// 判断输入的原密码是否正确
		String oldPassword = getParamStringValue(params, "oldPassword", 0);
		if (!oldPassword.equals(datas.get(0).get("passWord"))) {
			data.put("result", ServiceResultConfig.SUCCESS);
			data.put("message", "原密码输入错误");
		} else {

			// 更新用户密码
			String newPassword = getParamStringValue(params, "newPassword", 0);
			param.put("passWord", newPassword);
			try {
				session = sqlSessionFactory.getInstance().getSession();
				session.execute("updatePassword", param, datas);
				data.put("result", ServiceResultConfig.SUCCESS);
				data.put("message", "密码修改成功");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	/**
	 * 查询邮箱是否被注册
	 * 
	 * @zclong
	 * @2017年8月25日
	 * @ReturnType: void
	 * @param params
	 * @param datadisPlay
	 */
	@SuppressWarnings("unchecked")
	private void checkEmail(Map<String, Object[]> params, Map<String, Object> data) {
		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		String email = getParamStringValue(params, "email", 0);

		if (email == null || email.trim().isEmpty()) {
			data.put("email_msg", "邮箱不能为空！");
			data.put("result", FAILED);
			return;
		} else if (!email.matches(EMAIL_REGEX)) {
			data.put("email_msg", "邮箱格式错误！");
			data.put("result", FAILED);
			return;
		} else {
			try {
				param.put("email", email);
				Session session = sqlSessionFactory.getInstance().getSession();
				session.execute("queryEmail", param, datas);
				if (null == datas || datas.isEmpty()) {
					data.put("email_msg", "success");
					data.put("result", SUCCESS);
					return;
				} else {
					data.put("email_msg", "error");
					data.put("result", FAILED);
					return;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 用户注册
	 * 
	 * @zclong
	 * @2017年8月25日
	 * @ReturnType: void
	 * @param params
	 * @param data
	 */
	@SuppressWarnings("unchecked")
	private void register(Map<String, Object[]> params, Map<String, Object> data) {
		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		String email = getParamStringValue(params, "email", 0);
		String username = getParamStringValue(params, "username", 0);
		String password = getParamStringValue(params, "password", 0);
		String repassword = getParamStringValue(params, "repassword", 0);
		String sex = getParamStringValue(params, "sex", 0);
		String tel = getParamStringValue(params, "tel", 0);
		String question = getParamStringValue(params, "question", 0);
		String answer = getParamStringValue(params, "answer", 0);
		String card = getParamStringValue(params, "card", 0);
		String birthday = card.substring(6, 14);
		String personAddress = getParamStringValue(params, "personAddress", 0);
		String workAddress = getParamStringValue(params, "wordAddress", 0);

		data.remove("error_msg");
		// 邮箱验证
		if (email == null || email.trim().isEmpty()) {
			data.put("error_msg", "邮箱不能为空！");
			data.put("result", FAILED);
			return;
		} else if (!email.matches(EMAIL_REGEX)) {
			data.put("error_msg", "邮箱格式错误！");
			data.put("result", FAILED);
			return;
		} else {
			try {
				param.put("email", email);
				Session session = sqlSessionFactory.getInstance().getSession();
				session.execute("queryEmail", param, datas);
				if (null != datas) {
					data.put("email_msg", "邮箱已被注册");
					data.put("result", FAILED);
					return;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// 密码验证
		if (password == null || password.trim().isEmpty()) {
			data.put("error_msg", "密码不能为空！");
			data.put("result", FAILED);
			return;
		} else if (password.length() < 6 || password.length() > 10) {
			data.put("error_msg", "密码长度为6-10之间！");
			data.put("result", FAILED);
			return;
		}

		// 重复密码验证
		if (repassword == null || repassword.trim().isEmpty()) {
			data.put("error_msg", "密码不能为空！");
			data.put("result", FAILED);
			return;
		} else if (!repassword.equals(password)) {
			data.put("error_msg", "与原密码不同！");
			data.put("result", FAILED);
			return;
		}

		// 电话验证
		if (tel == null || tel.trim().isEmpty()) {
			data.put("error_msg", "电话号码不能为空！");
			data.put("result", FAILED);
			return;
		} else if (!tel.matches("^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17([0,1,6,7,]))|(18[0-2,5-9]))\\d{8}$")) {
			data.put("error_msg", "请输入正确的电话号码！");
			data.put("result", FAILED);
			return;
		}
		// 姓名验证
		if (username == null || username.trim().isEmpty()) {
			data.put("error_msg", "姓名不能为空！");
			data.put("result", FAILED);
			return;
		} else if (!username.matches("[\\u4e00-\\u9fa5]+")) {
			data.put("error_msg", "请输入真实姓名！");
			data.put("result", FAILED);
			return;
		}

		// 密保问题验证
		if (answer == null || answer.trim().isEmpty()) {
			data.put("error_msg", "密保不能为空！");
			data.put("result", FAILED);
			return;
		}

		// 身份证验证
		if (card == null || card.trim().isEmpty()) {
			data.put("error_msg", "身份证不能为空！");
			data.put("result", FAILED);
			return;
		} else if (!card.matches(IDCARD)) {
			data.put("error_msg", "身份证格式错误！");
			data.put("result", FAILED);
			return;
		}

		// 个人地址问题验证
		if (personAddress == null || personAddress.trim().isEmpty()) {
			data.put("error_msg", "个人不能为空！");
			data.put("result", FAILED);
			return;
		}

		// 工作地址问题验证
		if (workAddress == null || workAddress.trim().isEmpty()) {
			data.put("error_msg", "工作地址不能为空！");
			data.put("result", FAILED);
			return;
		}

		if (null != data.get("error_msg")) {
			data.put("result", FAILED);
			return;
		} else {
			try {
				param.put("email", email);
				param.put("username", username);
				param.put("password", password);
				param.put("sex", sex);
				param.put("tel", tel);
				param.put("question", question);
				param.put("answer", answer);
				param.put("card", card);
				param.put("birthday", birthday);
				param.put("personAddress", personAddress);
				param.put("workAddress", workAddress);
				Session session = sqlSessionFactory.getInstance().getSession();
				session.execute("addUser", param, datas);
				System.out.println(datas);
				if (null == datas || datas.isEmpty()) {
					data.put("email_msg", "success");
					data.put("result", SUCCESS);
					return;
				} else {
					data.put("email_msg", "error");
					data.put("result", FAILED);
					return;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 注销
	 * 
	 * @zclong
	 * @2017年8月27日
	 * @ReturnType: void
	 * @param params
	 * @param data
	 */
	private void logout(Map<String, Object[]> params, Map<String, Object> data) {
	    Map<String, Object> param = new HashMap<String, Object>(); //用来封装传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList();  // 用来接收数据库返回回来的 
        
        int userID = Integer.parseInt(getParamStringValue(params,"userID",0).trim());
        
        param.put("status", 2); 
        param.put("userID", userID);
        try {
            Session session = sqlSessionFactory.getInstance().getSession();
            session.execute("updateUserStatus", param, datas); // 用户登录后改变 账号状态为离线状态
        } catch (Exception e) {
            e.printStackTrace();
        } 
        data.put("result", EXIT);   //注销
	}

	/**
	 * 角色申请
	 * 
	 * @param params
	 * @param data
	 */
	@SuppressWarnings("unchecked")
	protected void roleApplication(Map<String, Object[]> params, Map<String, Object> data) {
		String roleID = getParamStringValue(params, "roleID", 0);

		String userID = getParamStringValue(params, "userID", 0);
		// 得到上传文件
		File[] files = (File[]) params.get("file");
		if (files == null) {
			data.put("message", "文件过大");
			data.put("result", SUCCESS);
			return;
		}
		// 得到文件的绝对路径
		String fileUrl = files[0].getAbsolutePath();

		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		param.put("applyObjectID", roleID);
		param.put("applyType", 0);
		param.put("userID", Integer.parseInt(userID));
		param.put("fileUrl", fileUrl);
		param.put("applyStatus", 2);// 表示该申请是待审核
		param.put("applicationTime", DateUtils.getNowTime());

		Session session;
		try {
			session = sqlSessionFactory.getInstance().getSession();
			session.execute("addApply", param, datas);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		data.put("message", "申请成功,请耐心等待管理员审核");
		userInfo(params, data);//显示个人信息
		data.put("result", SUCCESS);
	}

	/**
	 * 检验密保答案是否正确
	 * 
	 * @param params
	 * @param data
	 */
	@SuppressWarnings("unchecked")
	protected void checkQuestion(Map<String, Object[]> params, Map<String, Object> data) {

		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		String userID = getParamStringValue(params, "userID", 0);
		String passwordQuestion = getParamStringValue(params, "passwordQuestion", 0);
		// int id=Integer.parseInt(getParamStringValue(params, "id", 0));
		String newQueston = getParamStringValue(params, "newQuestion", 0);

		param.put("userID", userID);

		if (passwordQuestion == null || passwordQuestion.trim().isEmpty()) {
			data.put("error_msg", "error");
			data.put("result", FAILED);
			return;
		} else {
			try {
				Session session = sqlSessionFactory.getInstance().getSession();
				session.execute("queryUserByID", param, datas);
				if (!datas.get(0).get("passwordQuestion").equals(passwordQuestion)) {
					data.put("email_msg", "error");
					data.put("result", FAILED);
					return;
				}
				/*
				 * else{ //param.put("id", id); param.put("passwordQuestion",
				 * newQueston); session.execute("updateQuestion", param, datas);
				 * data.put("message", "修改密保成功"); data.put("result", SUCCESS);
				 * return; }
				 */
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@SuppressWarnings("unchecked")
	protected void updateQuestion(Map<String, Object[]> params, Map<String, Object> data) {
		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		String userID = getParamStringValue(params, "userID", 0);
		int id = Integer.parseInt(getParamStringValue(params, "id", 0));
		String newQueston = getParamStringValue(params, "newQuestion", 0);

		System.out.println("userID");

		param.put("userID", userID);
		param.put("id", id);
		param.put("passwordQuestion", newQueston);
		try {

			Session session = sqlSessionFactory.getInstance().getSession();

			session.execute("updateQuestion", param, datas);

			userInfo(params, data);//显示用户信息

			data.put("message", "修改密保成功");
			data.put("result", SUCCESS);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 个人信息更新
	 * 
	 * @param params
	 * @param data
	 */
	protected void updateInfo(Map<String, Object[]> params, Map<String, Object> data) {

		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		// 获取参数
		String userID = getParamStringValue(params, "userID", 0);
		String phoneNumber = getParamStringValue(params, "phoneNumber", 0);
		String workAddress = getParamStringValue(params, "workAddress", 0);
		String sex = getParamStringValue(params, "sex", 0);
		String birthday = getParamStringValue(params, "birthday", 0);
		String province = getParamStringValue(params, "s_province", 0);
		String city = getParamStringValue(params, "s_city", 0);
		String county = getParamStringValue(params, "s_county", 0);
		String personAddress = getParamStringValue(params, "personAddress", 0);

		String address = personAddress.substring(province.length() + city.length() + county.length(),
				personAddress.length());

		personAddress = province + "/" + city + "/" + county + "/" + address;

		param.put("userID", userID);
		param.put("phoneNumber", phoneNumber);
		param.put("workAddress", workAddress);
		param.put("sex", sex);
		param.put("birthday", birthday);
		param.put("personAddress", personAddress);

		Session session = null;
		try {
			session = sqlSessionFactory.getInstance().getSession();
			session.execute("updateUserInfo", param, datas);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();

		} catch (ConfigurationException e) {
			logger.error("更新个人信息失败");
			e.printStackTrace();

		} finally {
			session.releaseConnection();
		}

		userInfo(params, data);//显示个人信息
		data.put("message", "修改个人信息成功");
		data.put("result", SUCCESS);
		logger.debug("修改个人信息");

	}

	/**
	 * 申请解冻
	 * 
	 * @param params
	 * @param data
	 */
	@SuppressWarnings("unchecked")
	private void applyThaw(Map<String, Object[]> params, Map<String, Object> data) {
		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		String reason = getParamStringValue(params, "reason", 0);
		String email = getParamStringValue(params, "email", 0);

		param.put("email", email);

		try {
			Session session = sqlSessionFactory.getInstance().getSession();
			session.execute("queryEmail", param, datas);
			if (datas != null) {
				int userID = (int) datas.get(0).get("userID");
				param.put("userID", userID);
				param.put("applyObjectID", userID);
			}

			param.put("reason", reason);
			param.put("applyType", 1);// 表示申请时解冻申请
			param.put("applicationTime", DateUtils.getNowTime());
			param.put("applyStatus", 2);// 表示申请状态是待审核

			session.execute("applyThaw", param, datas);

			data.put("message", "申请成功,请耐心等待管理员审核");
			data.put("result", SUCCESS);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 显示所有密保
	 * 
	 * @param params
	 * @param data
	 */
	@SuppressWarnings("unchecked")
	private void securityQuestionManage(Map<String, Object[]> params, Map<String, Object> data) {
		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的
		 Session session = null;
		try {
			session = sqlSessionFactory.getInstance().getSession();
			session.execute("queryQuestion", param, datas);
			if (datas != null) {
				data.put("datas", datas);
				data.put("result", SUCCESS);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			//释放会话
            session.releaseConnection();
		}
	}

	/**
	 * 删除密保
	 * 
	 * @param params
	 * @param data
	 */
	@SuppressWarnings("unchecked")
	private void deleteQuestion(Map<String, Object[]> params, Map<String, Object> data) {
		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		String id = getParamStringValue(params, "id", 0);
		param.put("id", id);
		try {
			Session session = sqlSessionFactory.getInstance().getSession();
			boolean flag = session.execute("deleteQuestion", param, datas);
			// 判断是否删除成功
			if (flag) {
				data.put("question_msg", "success");
			} else {
				data.put("question_msg", "failed");
			}
			data.put("result", SUCCESS);
			//释放会话
            session.releaseConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	private void addQuestion(Map<String, Object[]> params, Map<String, Object> data) {
		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		String question = getParamStringValue(params, "question", 0);
		param.put("question", question);
		try {
			Session session = sqlSessionFactory.getInstance().getSession();
			session.execute("addQuestion", param, datas);
			session.execute("queryQuestion", param, datas);
			if (datas != null) {
				data.put("datas", datas);
				data.put("result", SUCCESS);
			}
			data.put("result", SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 找回密码
	 * 
	 * @param params
	 * @param data
	 */
	@SuppressWarnings("unchecked")
	private void findPassword(Map<String, Object[]> params, Map<String, Object> data) {
		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		String passWord = getParamStringValue(params, "password", 0);
		String email = getParamStringValue(params, "email", 0);
		param.put("email", email);
		param.put("passWord", passWord);

		Session session = null;
		try {
			session = sqlSessionFactory.getInstance().getSession();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String flag = getParamStringValue(params, "flag", 0);
		// flag=2:密保找回,flag=4邮箱找回
		if (flag.equals("2")) {

			String id = getParamStringValue(params, "id", 0);
			String passwordQuestion = getParamStringValue(params, "passwordQuestion", 0);

			param.put("passwordQuestion", passwordQuestion);
			param.put("id", id);

			session.execute("queryPasswordQuestion", param, datas);
			if (datas.size() != 0) {

				param.put("userID", datas.get(0).get("userID"));

				session.execute("updatePasswordByID", param, datas);
				data.put("message", "密码成功找回");

			} else {

				data.put("message", "你输入的密保问题或密保答案错误");
			}

		} else if (flag.equals("4")) {

			String code = getParamStringValue(params, "verification", 0);// 获取前台输入的验证码

			if (verification.get(email).equals(code)) {

				session.execute("updatePasswordByEmail", param, datas);

				data.put("message", "密码成功找回");
				verification.remove(email);
			} else {
				data.put("message", "你输入的验证码错误");
			}

		} else {
			data.put("message", "功能待开发中");
			data.put("result", SUCCESS);
		}
		data.put("result", SUCCESS);
	}

	/**
	 * 发送邮件
	 * 
	 * @param params
	 * @param data
	 */
	@SuppressWarnings("unchecked")
	private void sendEmail(Map<String, Object[]> params, Map<String, Object> data) {

		String email = getParamStringValue(params, "email", 0);
		// 如果map集合存在该邮箱的验证码移除
		if (verification.get(email) != null) {
			verification.remove("email");
		}
		// 随机生成0-9的四位验证码
		String text = "";
		for (int i = 0; i < 4; i++) {
			int x = (int) (Math.random() * 9);
			text += x;
		}

		verification.put(email, text);

		try {
			SendEmail.init(null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 进行初始化,设置邮箱配置文件的路径，如果为空，默认为email_template.properties在类路径下
		String subject = SendEmail.getSubject("subject");// 对应配置文件中的subject
		String content = SendEmail.getContent("content", text);// 对应配置文件中的content
		Mail mail = SendEmail.getMail(email, subject, content);
		SendEmail.sendMail(mail);

		data.put("email_msg", "success");
		data.put("result", SUCCESS);
	}

	private void showUserList(Map<String, Object[]> params, Map<String, Object> data) {

		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		try {
			Session session = sqlSessionFactory.getInstance().getSession();
			session.execute("showUserList", param, datas);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
		List<HashMap<String, Object>> user = new ArrayList();
		List<HashMap<String, Object>> lab = new ArrayList();
		List<HashMap<String, Object>> operator = new ArrayList();
		List<HashMap<String, Object>> admin = new ArrayList();
		for (HashMap<String, Object> hashMap : datas) {
			int roleID = (int) hashMap.get("roleID");
			if (roleID == 1) {
				user.add(hashMap);
			} else if (roleID == 2) {
				operator.add(hashMap);
			} else if (roleID == 3) {
				lab.add(hashMap);
			}else if(roleID == 4){
				admin.add(hashMap);
			}
		}

		data.put("user", user);
		data.put("operator", operator);
		data.put("lab", lab);
		data.put("admin", admin);
		data.put("result", SUCCESS);
		logger.debug("显示用户组");

	}

	/**
	 * 冻结用户后自动解冻
	 * 
	 * @param freeze
	 * @param params
	 * @param data
	 * @throws ClassNotFoundException
	 * @throws DocumentException
	 * @throws ConfigurationException
	 */
	void freezeAndThaw(Freeze freeze, Map<String, Object[]> params, Map<String, Object> data)
			throws ClassNotFoundException, DocumentException, ConfigurationException {

		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		String freezeName = freeze.getName();
		int freezeTime = freeze.getTime();

		Date freezetime = org.apache.commons.lang3.time.DateUtils.addMilliseconds(new Date(), freezeTime);

		Session session = sqlSessionFactory.getInstance().getSession();
		//冻结用户的编号参数为personUserID
		String userID = getParamStringValue(params, "personUserID", 0);
		param.put("status", 0);
		param.put("freezeTime", freezetime);
		param.put("userID", userID);

		session.execute("FreezeORThawUser", param, datas);
		logger.debug("用户被冻结，原因：" + freezeName + "  截止到" + freezetime + "解冻");

		param.put("status", 2);
		new Timer().schedule(new TimerTask() {

			@Override
			public void run() {
				try {
					Date freezetime = org.apache.commons.lang3.time.DateUtils.addMilliseconds(new Date(), 0);
					param.put("freezeTime", freezetime);
					session.execute("FreezeORThawUser", param, datas);
					logger.debug("用户解冻");
				} catch (ConfigurationException e) {
					e.printStackTrace();
				}
			}
		}, freezeTime);
	}

	/**
	 * 管理员手动解冻用户
	 * 
	 * @param params
	 * @param data
	 * @throws DocumentException
	 * @throws ClassNotFoundException
	 * @throws ConfigurationException
	 */
	private void ThawUser(Map<String, Object[]> params, Map<String, Object> data)
			throws ClassNotFoundException, DocumentException, ConfigurationException {

		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		String userID = getParamStringValue(params, "personUserID", 0);
		Date freezetime = org.apache.commons.lang3.time.DateUtils.addMilliseconds(new Date(), 0);

		param.put("status", 2);
		param.put("freezeTime", freezetime);
		param.put("userID", userID);

		Session session = sqlSessionFactory.getInstance().getSession();
		session.execute("FreezeORThawUser", param, datas);
		data.put("result", SUCCESS);
		data.put("message", "解冻成功");
		logger.debug("用户解冻");
	}
	
	private void showPersonInfo(Map<String, Object[]> params, Map<String, Object> data){
		userInfo(params, data);
		data.put("result", SUCCESS);
		logger.debug("查看userID："+getParamStringValue(params, "PersonUserID", 0)+"详细信息");
	}
	
	private void adminFreezeUser(Map<String, Object[]> params, Map<String, Object> data){
		try {
			freezeAndThaw(Freeze.adminSetFreeze, params, data);
		} catch (ClassNotFoundException | ConfigurationException | DocumentException e) {
			e.printStackTrace();
			logger.debug("冻结失败");
		}
		data.put("result", SUCCESS);
		data.put("message", "冻结成功");
		
	}
	/**
	 * 得到所有管理员的申请解冻信息
	 * @param params
	 * @param data
	 */
	private void showAdminApplyThaw(Map<String, Object[]> params, Map<String, Object> data){
		
		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		
		showAllUserApplyThawInfo(param, datas, params, data);
		
		List<HashMap<String, Object>> pass = new ArrayList(); 
		List<HashMap<String, Object>> audit = new ArrayList(); 
		List<HashMap<String, Object>> refuse = new ArrayList(); 
		List<HashMap<String, Object>> all = new ArrayList(); 
		
		for (HashMap<String, Object> hashMap : datas) {
			int status = (int) hashMap.get("applyStatus");
			int roleID = (int) hashMap.get("roleID");
			if(status==2&&roleID==4){  //管理员的解冻申请带审核
				audit.add(hashMap);
				all.add(hashMap);
			}else if(status==0&&roleID==4){ //管理员的解冻申请拒绝
				refuse.add(hashMap);
				all.add(hashMap);
			}else if(status==1&&roleID==4){ //管理员的解冻申请通过
				pass.add(hashMap);
				all.add(hashMap);
			}
		}
		
		data.put("pass", pass);
		data.put("audit", audit);
		data.put("refuse", refuse);
		data.put("all", all);
		data.put("result", SUCCESS);
	}
	
	/**
	 * 得到所有用户的申请解冻的请求信息
	 * @param param
	 * @param datas
	 * @param params
	 * @param data
	 */
	private void showAllUserApplyThawInfo(Map<String, Object> param,List<HashMap<String, Object>> datas 
	,Map<String, Object[]> params, Map<String, Object> data){
		
		param.put("applyType", 1);
		
		Session session = null;
		try {
			session = sqlSessionFactory.getInstance().getSession();
			session.execute("showAdminApplyThaw", param, datas);
		} catch (ClassNotFoundException | DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void showUserApplyThawInfo(Map<String, Object[]> params, Map<String, Object> data){
		
		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		String email = getParamStringValue(params, "email", 0);
		String roleID = getParamStringValue(params, "roleID", 0);
		int roleIDInt = Integer.parseInt(roleID);
		String applicationID = getParamStringValue(params, "applicationID", 0);
		int applicationIDInt = Integer.parseInt(applicationID);
		
		
		param.put("email", email);
		param.put("applicationID", applicationIDInt);
		param.put("applyType", 1);
		param.put("roleID", roleIDInt);
		
		Session session;
		try {
			session = sqlSessionFactory.getInstance().getSession();
			session.execute("showUserApplyThawInfo", param, datas);
		} catch (ClassNotFoundException | DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		data.put("result", SUCCESS);
		data.put("datas", datas);
		
		
	}
	
	
	private void showUserApplyThawReview(Map<String, Object[]> params, Map<String, Object> data){

		Map<String, Object> param = new HashMap<String, Object>(); // 用来封装传递给数据库的参数
		List<HashMap<String, Object>> datas = new ArrayList(); // 用来接收数据库返回回来的

		String reason = getParamStringValue(params, "reason", 0);
		String applicationID = getParamStringValue(params, "applicationID", 0);
		int applicationIDInt = Integer.parseInt(applicationID);
		String applyStatus = getParamStringValue(params, "applyStatus", 0);
		int applyStatusInt = Integer.parseInt(applyStatus);
		
		param.put("reason", reason);
		param.put("applicationID", applicationIDInt);
		param.put("applyStatus", applyStatusInt);
		
		Session session = null;
		try {
			session = sqlSessionFactory.getInstance().getSession();
			session.execute("showUserApplyThawReview", param, datas);
		} catch (ClassNotFoundException | DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		param.clear();
		param.put("applicationID", applicationIDInt);
		session.execute("getApplyUserID", param, datas);
		
		String[] userID = {datas.get(0).get("PersonUserID")+""};
		
		param.clear();
		params.put("personUserID", userID);
		try {
			ThawUser(params, data);
		} catch (ClassNotFoundException | ConfigurationException | DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		data.put("result", SUCCESS);
	}
	
}
